/*
 * @description: 数组相关工具
 * @Author: T.W
 * @Github: https://github.com/TernenceWu0702
 * @Date: 2021-07-22 13:55:28
 * @LastEditors: T.W
 * @LastEditTime: 2021-11-01 16:41:09
 */

/**
 * 判断是否是数组
 * @param arr 判断对象
 * @returns boolean
 */
export const arrJudge = (arr: any) => {
    if (Array.isArray(arr)) {
        return true
    }
}

/**
 * 数组去重
 * @param arr 数组
 * @returns 不重复的数组
 */
export const arrRemoveRepeat = (arr: []) => {
    return Array.from(new Set(arr))
}

/**
 * 数组排序
 * @param arr 数组
 * @param ascendFlag 是否升序，默认为true
 * @returns 已排序数组
 */
export const arrOrderAscend = (arr: [], ascendFlag: boolean = true) => {
    return arr.sort((a, b) => {
        return ascendFlag ? a - b : b - a
    })
}

/**
 * 数组最大值
 * @param arr 数组
 * @returns 最大值
 */
export const arrMax = (arr: []) => {
    return Math.max(...arr)
}

/**
 * 数组求和
 * @param arr number数组
 * @returns sum
 */
export const arrSum = (arr: [number]) => {
    return arr.reduce((prev: number, cur: number) => {
        return prev + cur
    }, 0)
}

/**
 * 对象数组求和
 * @param arrObj 对象数组
 * @param key 求和的对象键值
 * @returns sum
 */
export const arrObjSum = (arrObj: [object], key: string) => {
    return arrObj.reduce((prev, cur) => {
        return prev + cur[key]
    }, 0)
}

/**
 * 合并数组，目前合并一维
 * @param arr1 被合并数组
 * @param arr2 被合并数组
 * @returns 合并后数组
 */
export const arrConcat = (arr1: [], arr2: []) => {
    return [...arr1, ...arr2]
}

/**
 * 判断是否包含某值
 * @param arr 数组
 * @param value 目标值
 * @returns boolean
 */
export const arrIncludeValue = (arr: [any], value: any) => {
    return arr.includes(value)
}

/**
 * 数组并集，只支持一维数组
 * @param arr1 数组
 * @param arr2 数组
 * @returns 数组
 */
export const arrAndSet = (arr1: [], arr2: []) => {
    return arr1.concat(arr2.filter(v => !arr1.includes(v)))
}

/**
 * 数组交集，只支持一维数组
 * @param arr1 数组
 * @param arr2 数组
 * @returns 交集数组
 */
export const arrIntersection = (arr1: [], arr2: []) => {
    return arr1.filter(v => arr2.includes(v))
}

/**
 * 数组差集，只支持一维数组
 * @param arr1 数组
 * @param arr2 数组
 * @returns 差集数组
 * eg: [1,2,3] [2,3,4] => [1,4]
 */
export const arrDifference = (arr1: [], arr2: []) => {
    return arr1.concat(arr2).filter(v => !(arr1.includes(v) && arr2.includes(v)))
}

/**
 * 对象数组根据对象某个属性分组
 * @param list 对象数组
 * @param attr 属性名称
 * @returns 新数组
 */
export function ArrayGrouping(list, attr) {
    let data;
    list.forEach((element) => {
        const index = data.findIndex((item) => item[attr] === element[attr]);
        if (index > -1) {
            data[index]["group"].push(element);
        } else {
            data.push({
                [attr]: element[attr],
                "group": [element],
            });
        }
    });
    return data;
}

/**
 * @description: 根据属性去重数组
 * @param {*} arr 去重的数组
 * @param {any} fn 去重的key
 * @return {*} 新数组
 * @example arrUniqueByAttr([{name:'1111'},{name:'1111'},{name:'222'},{name:'333'}],'name') => [{name:'1111'},{name:'222'},{name:'333'}
 */
export const arrUniqueByAttr = (arr: [], fn: any) => {
    return arr.filter((element, index, array) => array.findIndex(row => {
        return typeof fn === "function" ? fn(row) === fn(element) : row[fn] === element[fn]
    }) === index)
}

/**
 * @description: 找出数组中该属性最小值的一列
 * @param {*} arr 数组
 * @param {string} key 关键属性
 * @return {*} 数组
 * @example arrMinByAttr([{num:55},{num:541},{num:41}],'num')  =>  {num: 41}
 */
export const arrMinByAttr = (arr: [], key: string) => {
    return arr.find(item => item[key] === Math.min.apply(Math, arr.map(row => row[key])))
}

/**
 * @description: 找出数组中该属性最大值的一列
 * @param {*} arr 数组
 * @param {string} key 关键属性
 * @return {*} 数组
 * @example arrMinByAttr([{num:55},{num:541},{num:41}],'num')  =>  {num: 541}
 */
export const areMaxByAttr = (arr: [], key: string) => {
    return arr.find(item => item[key] === Math.max.apply(Math, arr.map(row => row[key])))
}

/**
 * @description: 扁平化数组 ==> 树形结构
 * @param {array} array 数组
 * @param {array} options 配置
 * @param {String} options.pid 父级id名
 * @param {String} options.id 自己id名
 * @param {String} options.children 子集数组名
 * @returns {*} 树形结构数组
 */
export const convert = (array: Object[], options: Object) => {
    const { children, pid, id } = Object.assign({
        children: 'children',
        pid: 'pid',
        id: 'id'
    }, options)
    const _arr = array.filter(item => {
        var child = array.filter(child => {
            return child[pid] === item[id]
        })
        item[children] = child
        return item[pid] === 0
    })
    return _arr;
}


const getNodeMap = (node, parentNode, childName = "children") => {
    node.parentNode = parentNode;
    const nodeMap = [node];
    if (node[childName] && node[childName].length) {
        node[childName].forEach(item => nodeMap.push(...getNodeMap(item, node, childName)));
    }
    return nodeMap;
};

/**
 * @description: 树形结构 ==> 扁平化
 * @param {any} tree 数组
 * @param {*} childName 子集数组名
 * @return {*} 扁平化数组
 */
export const convertFlat = (tree: any[], childName = "children") => {
    if (!(tree instanceof Array)) return;
    const treeMap: any[] = [];
    tree.forEach(node => {
        treeMap.push(...getNodeMap(node, tree, childName));
    });
    return treeMap;
}

/**
 * @description: 数组乱序
 * @param {any} arr
 * @return {*}
 */
export const arrScrambling = (arr: any[]): any[] => {
    for (let i = 0; i < arr.length; i++) {
        const randomIndex: number = Math.round(Math.random() * (arr.length - 1 - i)) + i;
        [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
    }
    return arr;
}

/**
 * @description: 数组扁平化
 * @param {any} arr
 * @return {*}
 */
export const flatten = (arr: any[]): any[] => {
    let result: any[] = [];
    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            result = result.concat(flatten(arr[i]));
        } else {
            result.push(arr[i]);
        }
    }
    return result;
}

/**
 * @description: 数组中获取随机数
 * @param {any} arr
 * @return {*}
 */
export const sample = (arr: any[]): any => {
    return arr[Math.floor(Math.random() * arr.length)];
}